package com.leetcode;

import com.study.common.ListNode;

/**
 * @program: leetcode
 * @author: jzhou
 * @date: 2022-11-16 13:54
 * @version: 1.0
 * @description: 合并两个有序链表
 * 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
 **/
public class MergeTwoLists {
    public static void main(String[] args) {
        ListNode node6 = new ListNode(4, null);
        ListNode node5 = new ListNode(3, node6);
        ListNode node3 = new ListNode(1, node5);
        ListNode node4 = new ListNode(4, null);
        ListNode node2 = new ListNode(2, node4);
        ListNode node1 = new ListNode(1, node2);
//        ListNode node = mergeTwoLists(node1,node3);
        ListNode node = recursive(node1,node3);
        System.out.println(node);
    }

    private static ListNode mergeTwoLists(ListNode node1, ListNode node2) {
        if (node1 == null) return node2;
        if (node2 == null) return node1;
        ListNode resultNode = new ListNode(0,null);
        ListNode node = resultNode;
        while (node1 != null && node2 != null){
            if (node1.value < node2.value){
                node.next = node1;
                node1 = node1.next;
            }else {
                node.next = node2;
                node2 = node2.next;
            }
            node = node.next;
        }
        if (node1 != null) node.next = node1;
        if (node2 != null) node.next = node2;
        return resultNode.next;
    }

    private static ListNode recursive(ListNode node1, ListNode node2){
        if (node1 == null) return node2;
        if (node2 == null) return node1;
        if (node1.value < node2.value){
            node1.next = recursive(node1.next,node2);
            return node1;
        }else {
            node2.next = recursive(node1,node2.next);
            return node2;
        }
    }
}
